<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="600px" top="10vh" @close='close' class="ruleDialog">
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" label-width="120px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('类型')" class="ruleTypeForm" prop="proto_type">
          <el-radio-group v-model="record.proto_type" @change="protoTypeChange">
            <el-radio label="0" class="deepfilts">{{$t('精确过滤')}}</el-radio>
            <el-radio label="1" class="flits">{{$t('通用过滤')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('协议/应用')" class="ruleTypeForm" prop="proto" v-show="record.proto_type == '0'">
          <el-select v-model="record.proto" ref="proto" size='small' filterable @change="protoChange">
            <el-option v-for="(value, key) in protoList" :key="key" :label="key" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label="$t('协议/应用')" class="ruleTypeForm" prop="proto" v-show="record.proto_type == '1'">
        <el-select v-model="record.proto" size='small' filterable>
          <el-option v-for="item in AgreementList" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-form-item> -->
        <el-form-item :label="$t('协议/应用')" class="ruleTypeForm" prop="proto" v-show="record.proto_type == '1'">
          <el-select v-model="record.proto" prop="proto" ref="proto" size='small' filterable v-el-select-loadmore="loadmore" :filter-method="datafilter" @visible-change='visibleChange'>
            <el-option v-for="item in AgreementListShow" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('动作')" class="ruleTypeForm" prop="action">
          <el-select v-model="record.action" ref="action" size='small' filterable clearable>
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('匹配方向')" class="ruleTypeForm" prop="match_direction" v-if="record.proto_type == '0' && exact.includes(record.proto)">
          <el-select v-model="record.match_direction" ref="matchDirection" size='small'>
            <el-option v-for="(value, key) in protoList[record.proto]" :key="key" :label="value" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('匹配选项')" class="ruleTypeForm" prop="match_option" v-if="record.proto_type == '0' && currency.includes(record.proto)">
          <el-select v-model="record.match_option" ref="matchOption" size='small'>
            <el-option v-for="(value, key) in protoList[record.proto]" :key="key" :label="value" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('关键字')" prop="content">
          <el-input v-emoji v-model="record.content" :autosize="{ minRows: 4 }" size='small' ref="content" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
          <div class="tip-context">{{$t('多个关键字用逗号隔开，最多支持3个关键字，多个关键字之间是且的关系，需要同时满足，每个关键字的长度需大于1小于65')}}</div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="innerAddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="innerAddClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addBlackRule, getBlacklistAgreement } from '@/api/safe/black'
import { texttextClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'RuleDialog',
  directives: {
    'el-select-loadmore': {
      bind (el, binding) {
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function () {
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        proto_type: '0',
        proto: 'http',
        action: 'alert',
        match_direction: 'download',
        match_option: '-',
        content: ''
      },
      recordCopy: {
        proto_type: '0',
        proto: 'http',
        action: 'alert',
        match_direction: 'download',
        match_option: '-',
        content: ''
      },
      pageSize: 200,
      AgreementListShow: [],
      AgreementList: [],
      parentData: {},
      protoList: {
        'http': {
          'download': this.$t('下载'),
          'upload': this.$t('上传')
        },
        'ftp': {
          'both': this.$t('所有'),
          'download': this.$t('下载'),
          'upload': this.$t('上传'),
          'cmd': this.$t('命令')
        },
        'smtp': {
          'All': this.$t('所有'),
          'From': this.$t('发件人'),
          'To': this.$t('收件人'),
          'Subject': this.$t('主题'),
          'Filename': this.$t('文件名'),
          'Body': this.$t('正文')
        },
        'pop3': {
          'All': this.$t('所有'),
          'From': this.$t('发件人'),
          'To': this.$t('收件人'),
          'Subject': this.$t('主题'),
          'Filename': this.$t('文件名'),
          'Body': this.$t('正文')
        },
        'imap': {
          'All': this.$t('所有'),
          'From': this.$t('发件人'),
          'To': this.$t('收件人'),
          'Subject': this.$t('主题'),
          'Filename': this.$t('文件名'),
          'Body': this.$t('正文')
        },
        'telnet': {
          'both': this.$t('所有'),
          'download': this.$t('服务器'),
          'upload': this.$t('客户端')
        }
      },
      exact: ['http', 'ftp', 'telnet'],
      currency: ['smtp', 'pop3', 'imap'],
      typeList: [ //   alert/deny  告警/阻断
        { value: 'alert', label: this.$t('告警') },
        { value: 'deny', label: this.$t('阻断') }
      ],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  computed: {
    change () {
      const { proto, proto_type } = this.record
      return {
        proto, proto_type
      }
    }
  },
  watch: {
    'record.content': {
      handler (newVal) {
        if (newVal && newVal.length > 0) {
          this.record.content = newVal.replace(/[\r\n]/g, '')
        }
      },
      immediate: true
    },
    change (val) {
      if (val.proto_type === '0' && this.exact.includes(val.proto)) {
        this.$nextTick(() => {
          const selectData = ['matchDirection']
          selectClass(this.$refs, selectData)
        })
      } else if (val.proto_type === '1') {
        this.$nextTick(() => {
          const selectData = ['proto']
          selectClass(this.$refs, selectData)
        })
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const textdata = ['content']
        const selectData = ['proto', 'action', 'matchDirection']
        texttextClass(this.$refs, textdata)
        selectClass(this.$refs, selectData)
      })
      this.parentData = data
      getBlacklistAgreement().then(res => {
        if (res.status === 0) {
          this.AgreementList = res.data
          // this.changeSjgbs()
        }
      })
    },
    loadmore () {
      this.pageSize += 200
      this.changeSjgbs()
    },
    changeSjgbs () {
      if (!(this.AgreementListShow.length % 200)) {
        this.AgreementListShow = this.AgreementList.slice(0, this.pageSize < this.AgreementList.length ? this.pageSize : this.AgreementList.length)
      }
    },
    datafilter (query = '') { // 自定义的筛选出所输入值所匹配出的集合
      if (query) {
        let arr = this.AgreementList.filter((item) => {
          return item.includes(query)
        })
        if (arr.length > 100) {
          this.AgreementListShow = arr.slice(0, 100)
        } else {
          this.AgreementListShow = arr
        }
      } else {
        this.pageSize = 200
        this.AgreementListShow = this.AgreementList.slice(0, 200)
      }
    },
    protoChange (data) {
      if (this.exact.includes(data)) {
        this.record.match_option = '-'
        for (var item in this.protoList[data]) {
          this.record.match_direction = item
          break
        }
      } else if (this.currency.includes(data)) {
        this.record.match_direction = '-'
        for (var item2 in this.protoList[data]) {
          this.record.match_option = item2
          break
        }
      }
    },
    visibleChange (data) {
      this.pageSize = 200
      this.AgreementListShow = this.AgreementList.slice(0, 200)
    },
    protoTypeChange (data) {
      switch (data) {
        case '0':
          this.record.proto = 'http'
          break
        case '1':
          this.record.proto = this.AgreementList[0]
          break
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let contentList = this.record.content.split(',')
          if (contentList.length > 3) {
            this.$messages.error(this.$t('关键字错误，输入关键字部分最多支持3个，以英文逗号隔开，每个内容大小最多支持64'))
            return
          }
          for (let item of contentList) {
            if (item.length > 64) {
              this.$messages.error(this.$t('关键字错误，输入关键字部分最多支持3个，以英文逗号隔开，每个内容大小最多支持64'))
              return
            }
          }
          if (this.parentData.id) {
            var formDataEdit = JSON.stringify(Object.assign({}, this.record))
            addBlackRule({ name: this.parentData.old_name, rule_map: formDataEdit }).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('添加成功'),
                  type: 'success'
                })
                this.$emit('listData')
                this.close()
              }
            })
          } else {
            var formData = Object.assign({}, this.record)
            var updataData = true
            if (this.parentData.rule_map && this.parentData.rule_map.length > 0) {
              this.parentData.rule_map.forEach((item, index) => {
                let r = JSON.parse(JSON.stringify(item))
                let l = JSON.parse(JSON.stringify(formData))
                delete r['rule_id']
                r = JSON.stringify(r)
                l = JSON.stringify(l)
                if (r === l) {
                  updataData = false
                }
              })
            }

            if (updataData) {
              this.$emit('listData', formData)
              this.close()
            } else { // 已添加该规则！
              this.$message({
                message: this.$t('已添加该规则！'),
                type: 'error'
              })
            }
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.parentData = {}
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.tip-context {
  color: #999;
  font-size: 12px;
  line-height: 24px;
}
</style>
